﻿using ML.IBusiness;
using ML.IRepository;
using ML.Entity;
using ML.Repository;
using ML.Utils;
using System.Linq;
using System.Collections.Generic;

namespace ML.Business
{
    /// <summary>
    /// 资金账户业务实现
    /// </summary>
    public class CapitalAccountBusiness : ICapitalAccountBusiness
    {
        private readonly ICapitalAccountRepository capitalAccountRepository;
        private readonly IOrderRepository orderRepository;
        public CapitalAccountBusiness(ICapitalAccountRepository _capitalAccountRepository, IOrderRepository _orderRepository)
        {
            capitalAccountRepository = _capitalAccountRepository;
            orderRepository = _orderRepository;
        }

        public Pager<CapitalAccountResponse> List(CapitalAccountSearch capitalAccountSearch)
        {
            //根据传递的条件查询
            Pager<CapitalAccountResponse> datas = capitalAccountRepository.List(capitalAccountSearch);
            foreach (var data in datas.rows)
            {
                data.ResidueMoney = data.Balance - data.Withdrawed;
            }
            return datas;
        }

        public BaseResult<CapitalAccountEntity> GetByMerchantId(string id)
        {

            CapitalAccountEntity data = capitalAccountRepository.GetByMerchantId(id);
            if (data == null)
            {
                return new BaseResult<CapitalAccountEntity>(202);
            }
            return new BaseResult<CapitalAccountEntity>(200, data);
        }

        public CapitalAccountResponse GetCollectInfo(string merchantId)
        {
            CapitalAccountResponse capitalAccountResponse = new CapitalAccountResponse();
            IEnumerable<CapitalAccountEntity> datas = capitalAccountRepository.GetCollectInfo(merchantId);
            var data = orderRepository.GetTrueOrderInfoByMerchantId(merchantId);
            if (datas.Count() > 0)
            {
                capitalAccountResponse.MerchantId = datas.FirstOrDefault().MerchantId;
                capitalAccountResponse.Balance = datas.Sum(c => c.Balance);
                capitalAccountResponse.Withdrawed = datas.Sum(c => c.Withdrawed);
                capitalAccountResponse.ResidueMoney = capitalAccountResponse.Balance - capitalAccountResponse.Withdrawed;
                capitalAccountResponse.OrderCount = data.Count();
            }
            return capitalAccountResponse;
        }
    }
}